package net.nagaseyasuhito.nicola.page;

import org.apache.wicket.authentication.AuthenticatedWebApplication;
import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.validation.IValidationError;
import org.apache.wicket.validation.ValidationError;

public class SignInPage extends BasePage {
	private static final long serialVersionUID = 1L;

	public SignInPage() {
		this.add(new SignInForm("signInForm"));
	}

	private class SignInForm extends Form {
		private static final long serialVersionUID = 1L;

		private String name;
		private String password;

		public SignInForm(String id) {
			super(id);
			this.setModel(new CompoundPropertyModel(this));

			this.add(new FeedbackPanel("feedback"));
			this.add(new TextField("name").setRequired(true));
			this.add(new PasswordTextField("password"));
			this.add(new Button("submit") {
				private static final long serialVersionUID = 1L;

				@Override
				public void onSubmit() {
					if(AuthenticatedWebSession.get().signIn(name, password)) {
						if(!this.continueToOriginalDestination()) {
							this.setResponsePage(AuthenticatedWebApplication.get().getHomePage());
						}
					}
					else {
						this.error((IValidationError) new ValidationError().addMessageKey("signInFailed"));
					}
				}
			});
		}
	}
}

